package com.bite.order.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

//@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setContentType("text/html;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        int errorCode = 429;
        String msg = "sentinel blocked by sentinel";
        if (e instanceof FlowException) {
            errorCode = 429;
            msg = "限流了";
        } else if (e instanceof DegradeException) {
            errorCode = 503;
            msg = "降级了";
        } else if (e instanceof AuthorityException) {
            errorCode = 403;
            msg = "授权失败";
        } else if (e instanceof ParamFlowException) {
            errorCode = 429;
            msg = "参数限流了";
        }
        writer.write(msg);
        writer.flush();
        writer.close();
        httpServletResponse.setStatus(errorCode);
    }
}
